package apiv1

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"github.com/spf13/viper"
	"go-shop-api/internal/service"
	"go-shop-api/internal/validate"
	"go-shop-api/pkg/e"
	"go-shop-api/pkg/serializer"
	"net/http"
)

func Index(c *gin.Context) {

	fmt.Println(viper.Get("app.key"))

	c.JSON(http.StatusOK, "hello world")
}

func Validator(c *gin.Context) {
	var vs service.ValidatorService
	if err := c.ShouldBind(&vs); err != nil {
		fmt.Println(vs)
		// 获取validator.ValidationErrors类型的errors
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			fmt.Println("this is no ok")
			// 非validator.ValidationErrors类型错误直接返回
			c.JSON(http.StatusBadRequest, serializer.NewResponse(e.InvalidParams, e.TipsOk, e.TipsNil, err.Error()))
			return
		}
		// validator.ValidationErrors类型错误则进行翻译
		//c.JSON(http.StatusBadRequest, serializer.NewResponse(e.InvalidParams, "error", errs.Translate(validate.GetValidatorTrans())))

		//    "data": {
		//        "ValidatorService.age": "age必须大于或等于1",
		//        "ValidatorService.email": "email为必填字段",
		//        "ValidatorService.name": "name为必填字段",
		//        "ValidatorService.password": "password为必填字段",
		//        "ValidatorService.re_password": "re_password为必填字段"
		//    }
		fmt.Println("this is ok")
		c.JSON(http.StatusBadRequest, serializer.NewResponse(e.InvalidParams, e.TipsOk, e.TipsNil, validate.RemoveTopStruct(errs.Translate(validate.GetValidatorTrans()))))
		// RemoveTopStruct() 效果：取消前缀

		//    "data": {
		//        "age": "age必须大于或等于1",
		//        "email": "email为必填字段",
		//        "name": "name为必填字段",
		//        "password": "password为必填字段",
		//        "re_password": "re_password为必填字段"
		//    }

		return

	}
	// 保存入库等业务逻辑代码...
	c.JSON(http.StatusOK, serializer.NewResponse(e.Success, e.TipsOk, e.TipsNil, ""))
	return
}
